In this project, you will apply unsupervised learning techniques to identify segments of the population that form the core customer base for a mail-order sales company in Germany. These segments can then be used to direct marketing campaigns towards audiences that will have the highest expected rate of returns. The data that you will use has been provided by our partners at Bertelsmann Arvato Analytics, and represents a real-life data science task.
This notebook will help you complete this task by providing a framework within which you will perform your analysis steps. In each step of the project, you will see some text describing the subtask that you will perform, followed by one or more code cells for you to complete your work. Feel free to add additional code and markdown cells as you go along so that you can explore everything in precise chunks. The code cells provided in the base template will outline only the major tasks, and will usually not be enough to cover all of the minor tasks that comprise it.
It should be noted that while there will be precise guidelines on how you should handle certain tasks in the project, there will also be places where an exact specification is not provided. There will be times in the project where you will need to make and justify your own decisions on how to treat the data. These are places where there may not be only one way to handle the data. In real-life tasks, there may be many valid ways to approach an analysis task. One of the most important things you can do is clearly document your approach so that other scientists can understand the decisions you've made.
At the end of most sections, there will be a Markdown cell labeled Discussion. In these cells, you will report your findings for the completed section, as well as document the decisions that you made in your approach to each subtask. Your project will be evaluated not just on the code used to complete the tasks outlined, but also your communication about your observations and conclusions at each stage.
# import libraries here; add more as necessary
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import re
from IPython.display import display
# magic word for producing visualizations in notebook
%matplotlib inline
%config InlineBackend.figure_format = 'retina'
There are four files associated with this project (not including this one):
Udacity_AZDIAS_Subset.csv: Demographics data for the general population of Germany; 891211 persons (rows) x 85 features (columns).Udacity_CUSTOMERS_Subset.csv: Demographics data for customers of a mail-order company; 191652 persons (rows) x 85 features (columns).Data_Dictionary.md: Detailed information file about the features in the provided datasets.AZDIAS_Feature_Summary.csv: Summary of feature attributes for demographics data; 85 features (rows) x 4 columnsEach row of the demographics files represents a single person, but also includes information outside of individuals, including information about their household, building, and neighborhood. You will use this information to cluster the general population into groups with similar demographic properties. Then, you will see how the people in the customers dataset fit into those created clusters. The hope here is that certain clusters are over-represented in the customers data, as compared to the general population; those over-represented clusters will be assumed to be part of the core userbase. This information can then be used for further applications, such as targeting for a marketing campaign.
To start off with, load in the demographics data for the general population into a pandas DataFrame, and do the same for the feature attributes summary. Note for all of the .csv data files in this project: they're semicolon (;) delimited, so you'll need an additional argument in your read_csv() call to read in the data properly. Also, considering the size of the main dataset, it may take some time for it to load completely.
Once the dataset is loaded, it's recommended that you take a little bit of time just browsing the general structure of the dataset and feature summary file. You'll be getting deep into the innards of the cleaning in the first major step of the project, so gaining some general familiarity can help you get your bearings.
# Load in the general demographics data.
azdias = pd.read_csv('Udacity_AZDIAS_Subset.csv', delimiter=';')
# Load in the feature summary file.
feat_info = pd.read_csv('AZDIAS_Feature_Summary.csv', delimiter=';')
# Check the structure of the data after it's loaded (e.g. print the number of
# rows and columns, print the first few rows).
azdias.shape
azdias.head(3)
azdias.info()
Tip: Add additional cells to keep everything in reasonably-sized chunks! Keyboard shortcut
esc --> a(press escape to enter command mode, then press the 'A' key) adds a new cell before the active cell, andesc --> badds a new cell after the active cell. If you need to convert an active cell to a markdown cell, useesc --> mand to convert to a code cell, useesc --> y.
The feature summary file contains a summary of properties for each demographics data column. You will use this file to help you make cleaning decisions during this stage of the project. First of all, you should assess the demographics data in terms of missing data. Pay attention to the following points as you perform your analysis, and take notes on what you observe. Make sure that you fill in the Discussion cell with your findings and decisions at the end of each step that has one!
The fourth column of the feature attributes summary (loaded in above as feat_info) documents the codes from the data dictionary that indicate missing or unknown data. While the file encodes this as a list (e.g. [-1,0]), this will get read in as a string object. You'll need to do a little bit of parsing to make use of it to identify and clean the data. Convert data that matches a 'missing' or 'unknown' value code into a numpy NaN value. You might want to see how much data takes on a 'missing' or 'unknown' code, and how much data is naturally missing, as a point of interest.
As one more reminder, you are encouraged to add additional cells to break up your analysis into manageable chunks.
print('feat_info shape:', feat_info.shape)
print('\nfeat_info head:')
display(feat_info.head())
print('\nInformation Levels:')
display(feat_info.information_level.unique())
print('\nTypes:')
display(feat_info['type'].unique())
print('\nMissing or Unknown Values')
display(feat_info.missing_or_unknown.unique())
azdias.isnull().sum().sum()
# Identify missing or unknown data values and convert them to NaNs.
def convert_missing_unknown_to_nan(df, features=feat_info):
"""
Identify missing or unknown data values in the data frame df and convert them to NaNs.
Arg: data frames df and features
Returns: converted data frame
"""
unknown_or_missing_vals = list(set(features.missing_or_unknown.unique()) - set(['[]']))
#print(unknown_or_missing_vals)
regex = re.compile(r'[-]?\d|[X]+')
for val in unknown_or_missing_vals:
if val == '[XX]':
feature_to_clean = features[features.missing_or_unknown == val].attribute.values
df[feature_to_clean] = df[feature_to_clean].replace(['XX'], np.nan)
elif val == '[-1,X]':
feature_to_clean = features[features.missing_or_unknown == val].attribute.values
df[feature_to_clean] = df[feature_to_clean].replace([-1, 'X'], np.nan)
elif val == '[-1,XX]':
feature_to_clean = features[features.missing_or_unknown == val].attribute.values
df[feature_to_clean] = df[feature_to_clean].replace([-1, 'XX'], np.nan)
else:
unknown_num_vals = regex.findall(val)
unknown_num_vals = list(map(int, unknown_num_vals))
feature_to_clean = features[features.missing_or_unknown == val].attribute.values
df[feature_to_clean] = df[feature_to_clean].replace(unknown_num_vals, np.nan)
return df
# Apply the convert_missing_unknown_to_nan function to the azdias dataframe
azdias = convert_missing_unknown_to_nan(azdias)
azdias.isnull().sum().sum()
How much missing data is present in each column? There are a few columns that are outliers in terms of the proportion of values that are missing. You will want to use matplotlib's hist() function to visualize the distribution of missing value counts to find these columns. Identify and document these columns. While some of these columns might have justifications for keeping or re-encoding the data, for this project you should just remove them from the dataframe. (Feel free to make remarks about these outlier columns in the discussion, however!)
For the remaining features, are there any patterns in which columns have, or share, missing data?
# Perform an assessment of how much missing data there is in each column of the
# dataset.
azdias.isnull().sum().hist(bins=15)
plt.xlabel('Number of Missing/unknown values')
plt.ylabel('Frequency');
# Investigate patterns in the amount of missing data in each column.
plt.figure(figsize=(12, 26))
ax = azdias.isnull().sum().sort_values().plot(kind='barh')
plt.axvline(x=200000, ls='-.', color='red');
# Features with more than 200000 missing values
remove_feats = list(azdias.columns[azdias.isnull().sum().values > 200000])
remove_feats
# Remove the outlier columns from the dataset. (You'll perform other data
# engineering tasks such as re-encoding and imputation later.)
azdias.drop(remove_feats, axis=1, inplace=True)
plt.figure(figsize=(12, 22))
azdias.isnull().sum().sort_values().plot(kind='barh')
plt.axvline(x=200000, ls='-.', color='red');
There appears to be patterns in the number of missing values, and it generally depends on the information level of features. The "FINANZ" and "SEMIO" features are both complete, with no missing values. The columns with more than 200000 missing values that were removed from the dataset are: "AGER_TYP", "GEBURTSJAHR", "TITEL_KZ", "ALTER_HH", "KK_KUNDENTYP", and "KBA05_BAUMAX".
Now, you'll perform a similar assessment for the rows of the dataset. How much data is missing in each row? As with the columns, you should see some groups of points that have a very different numbers of missing values. Divide the data into two subsets: one for data points that are above some threshold for missing values, and a second subset for points below that threshold.
In order to know what to do with the outlier rows, we should see if the distribution of data values on columns that are not missing data (or are missing very little data) are similar or different between the two groups. Select at least five of these columns and compare the distribution of values.
countplot() function to create a bar chart of code frequencies and matplotlib's subplot() function to put bar charts for the two subplots side by side.Depending on what you observe in your comparison, this will have implications on how you approach your conclusions later in the analysis. If the distributions of non-missing features look similar between the data with many missing values and the data with few or no missing values, then we could argue that simply dropping those points from the analysis won't present a major issue. On the other hand, if the data with many missing values looks very different from the data with few or no missing values, then we should make a note on those data as special. We'll revisit these data later on. Either way, you should continue your analysis for now using just the subset of the data with few or no missing values.
# Distribution of row-total missing values
azdias.isnull().sum(axis=1).hist();
# Rows with the highest row-total missing values
azdias.isnull().sum(axis=1).sort_values()[-10:]
azdias.iloc[azdias.isnull().sum(axis=1).sort_values()[-3:].index]
# Rows with the lowest row-total missing values
azdias.isnull().sum(axis=1).sort_values()[:10]
azdias.iloc[azdias.isnull().sum(axis=1).sort_values()[:3].index]
azdias.isnull().sum().sort_values()[:6]
# Six columns with zero missing values used to compare the distributions of
# values in the two groups below, obtained by dividing the azdias dataset based on
# the row-total missing values being more or at most equal to the threshold value of 25
dense_feats = azdias.isnull().sum().sort_values().keys()[:6]
dense_feats
azdias.ZABEOTYP.unique()
# Dividing the azdias dataset into two groups -
# one with row-total missing values at most 25 and another one with
# higher than 25
ind_below_trsh = azdias.isnull().sum(axis=1).values <=25
azdias_below_trsh = azdias.iloc[ind_below_trsh]
azdias_above_trsh = azdias.iloc[~ind_below_trsh]
# Proportions of the two groups relative to the original azdias dataset
prop_below = azdias_below_trsh.shape[0] / azdias.shape[0]
prop_above = azdias_above_trsh.shape[0] / azdias.shape[0]
print(prop_below, prop_above)
Note: about 89.5% of the original dataset are in azdias_below_trsh subset and about 10.5% of the original dataset are in the azdias_above_trsh subset.
# Compare the distribution of values for at least five columns where there are
# no or few missing values, between the two subsets.
def comparison_plot(vars):
n = len(vars)
for i in range(n):
plt.figure(figsize=(12, 3))
plt.subplot(1, 2, 1)
ax=sns.countplot(x=vars[i], data=azdias_above_trsh, palette='Oranges_r')
ax.set_xlabel('{} ({})'.format(vars[i], 'Above Threshold'), color='#e74c3c', size=12)
plt.subplot(1, 2, 2)
ax=sns.countplot(x=vars[i], data=azdias_below_trsh, palette='GnBu_d')
ax.set_xlabel('{} ({})'.format(vars[i], 'Below Threshold'), color='#3498db', size=12)
plt.tight_layout()
comparison_plot(dense_feats)
The above plots show that the data with lots of missing values in their rows (azdias_above_trsh) are qualitatively different from the data with few or no missing values in their rows (azdias_below_trsh). Alternatively, we can also use a Kolmogorov-Smirnov test to test each column against the null hypothesis. The lower the p-value the more we can assume that the two distributions are different.
from scipy.stats import ks_2samp
comp_df = pd.DataFrame(azdias.columns, columns=['col'])
def hypothesis_test(df1, df2, cols):
stats = []
pvalues = []
for col in cols:
counts_main = df1[col].value_counts().sort_index()
counts_drop = df2[col].value_counts().sort_index()
try:
ch = ks_2samp(counts_main, counts_drop)
stats.append(ch.statistic)
pvalues.append(ch.pvalue)
except:
stats.append(np.nan)
pvalues.append(np.nan)
return stats, pvalues
stats, pvalues = hypothesis_test(azdias_below_trsh, azdias_above_trsh, azdias_below_trsh.columns.values)
comp_df['stats'] = stats
comp_df['pvalues'] = pvalues
comp_df.head()
Thanks to the first reviewer for suggesting the hypothesis-test method above and the seaborn distplots below!
plt.figure(figsize=(100,100))
for i, col in enumerate(azdias.columns[:10]):
plt.subplot(5, 2, i+1)
sns.distplot(azdias_below_trsh[col][azdias_below_trsh[col].notnull()], label='below')
sns.distplot(azdias_above_trsh[col][azdias_above_trsh[col].notnull()], label='above')
plt.title('Distribution for column: {}'.format(col))
plt.legend();
Checking for missing data isn't the only way in which you can prepare a dataset for analysis. Since the unsupervised learning techniques to be used will only work on data that is encoded numerically, you need to make a few encoding changes or additional assumptions to be able to make progress. In addition, while almost all of the values in the dataset are encoded using numbers, not all of them represent numeric values. Check the third column of the feature summary (feat_info) for a summary of types of measurement.
In the first two parts of this sub-step, you will perform an investigation of the categorical and mixed-type features and make a decision on each of them, whether you will keep, drop, or re-encode each. Then, in the last part, you will create a new data frame with only the selected and engineered columns.
Data wrangling is often the trickiest part of the data analysis process, and there's a lot of it to be done here. But stick with it: once you're done with this step, you'll be ready to get to the machine learning parts of the project!
# How many features are there of each data type?
feat_info.type.value_counts()
For categorical data, you would ordinarily need to encode the levels as dummy variables. Depending on the number of categories, perform one of the following:
feat_info[feat_info.type == 'categorical']
# The categorical features less the features that were already removed in step 1.1.2
cat_feats = list(set(feat_info[feat_info.type == 'categorical'].attribute.values )-set(remove_feats))
cat_feats
df_cat = azdias_below_trsh[cat_feats]
df_cat.head()
# Assess categorical variables: which are binary, which are multi-level, and
# which one needs to be re-encoded?
df_cat.nunique()
# The binary categorical features will be kept and the multi-level categoricals (three or more values)
# will be dropped
retain_cat_feats = list(df_cat.nunique()[df_cat.nunique().values < 3].keys())
drop_cat_feats = list(set(cat_feats) - set(retain_cat_feats))
df_cat[retain_cat_feats].nunique()
Note: the feature OST_WEST_KZ has non-numeric values.
display(drop_cat_feats)
azdias_below_trsh.shape
# Drop the multi-level categoricals
azdias_below_trsh = azdias_below_trsh.drop(drop_cat_feats, axis=1)
# Re-encode the categorical variable with non-numeric values, namely, the "OST_WEST_KZ" feature
azdias_below_trsh['OST_WEST_KZ'] = azdias_below_trsh['OST_WEST_KZ'].map({'O':0, 'W':1})
azdias_below_trsh.OST_WEST_KZ.value_counts()
I have kept the binary categorical features and dropped the multi-level categorical variables (with three or more values). Among the five binary categorical variables all but one have numeric values, so I kept those as they are. For the one binary categorical variable with non-numeric values (OST_WEST_KZ), I re-encoded it numerically as 0 ("O") and 1 ("W").
There are a handful of features that are marked as "mixed" in the feature summary that require special treatment in order to be included in the analysis. There are two in particular that deserve attention; the handling of the rest are up to your own choices:
Be sure to check Data_Dictionary.md for the details needed to finish these tasks.
feat_info[feat_info.type=='mixed']
# Investigate "PRAEGENDE_JUGENDJAHRE" and engineer two new variables.
azdias_below_trsh.PRAEGENDE_JUGENDJAHRE.unique()
# generation -- by decade, and movement -- mainstream vs avantgrade
def genr(x):
"""
A function that captures generation (by decade) out of the PRAEGENDE_JUGENDJAHRE feature
INPUT:
the encoding of the PRAEGENDE_JUGENDJAHRE feature (a number between 1 and 15)
OUTPUT:
the decade of the feature (40 for 40s, 50 for 50s, etc.)
"""
if x is np.nan:
return np.nan
elif x in list(map(float, [1,2])):
return 40
elif x in list(map(float, [3,4])):
return 50
elif x in list(map(float, [5,6,7])):
return 60
elif x in list(map(float, [8,9])):
return 70
elif x in list(map(float, [10,11,12,13])):
return 80
elif x in list(map(float, [14,15])):
return 90
def movement(x):
"""
A function that captures MOVEMENT (mainstream vs. avantgarde) out of the PRAEGENDE_JUGENDJAHRE feature
Arg:
the encoding of the PRAEGENDE_JUGENDJAHRE feature (a number between 1 and 15)
Returns:
binary values (0 for 'Mainstream' and 1 for 'Avantgarde')
"""
if x is np.nan:
return np.nan
elif x in list(map(float, [1,3,5,8,10,12,14])):
return 0
elif x in list(map(float, [2,4,6,7,9,11,13,15])):
return 1
azdias_below_trsh['GENERATION']=azdias_below_trsh.PRAEGENDE_JUGENDJAHRE.map(genr)
azdias_below_trsh['MOVEMENT']=azdias_below_trsh.PRAEGENDE_JUGENDJAHRE.map(movement)
# Investigate "CAMEO_INTL_2015" and engineer two new variables.
azdias_below_trsh.CAMEO_INTL_2015.unique()
# wealth -- tens-place digit, life_stage -- ones-place digit
azdias_below_trsh.CAMEO_INTL_2015.isnull().sum()
def tens_digit(x):
if x is np.nan:
return np.nan
else:
return int(x[0])
def ones_digit(x):
if x is np.nan:
return np.nan
else:
return int(x[1])
azdias_below_trsh['WEALTH']=azdias_below_trsh.CAMEO_INTL_2015.map(tens_digit)
azdias_below_trsh['LIFE_STAGE']=azdias_below_trsh.CAMEO_INTL_2015.map(ones_digit)
mixed_feats = list(feat_info[feat_info.type=='mixed'].attribute.values)
mixed_feats = list(set(mixed_feats) - set(remove_feats))
mixed_feats
# Drop the mixed features from the one_hot_data including PRAEGENDE_JUGENDJAHRE and CAMEO_INTL_2015
azdias_below_trsh = azdias_below_trsh.drop(mixed_feats, axis=1)
With regards to the mixed-value features, I created two variables ("GENERATION" and "MOVEMENT") from the "PRAEGENDE_JUGENDJAHRE" feature using the genr and movement functions I wrote above. Similarly, I created two variables ("WEALTH" and "LIFE_STAGE") from the "CAMEO_INTL_2015" mixed-value feature using the tens_digit and ones_digit functions I wrote above that split the tens digit and ones digit of a two-digit number. Finally, I dropped all the mixed-value features including "PRAEGENDE_JUGENDJAHRE" and "CAMEO_INTL_2015" (after I derived the new variables mentioned above from them). The reason for dropping all mixed-value features was just for simplicity - some of the mixed features are fine-scale classifications and hence, have several possible values. Referencing the Data_Dictionary.md document was crucial for this step, particularly, in understanding the dimensions of the "PRAEGENDE_JUGENDJAHRE" and "CAMEO_INTL_2015" features, and it enabled me to write the genr and movement functions above.
In order to finish this step up, you need to make sure that your data frame now only has the columns that you want to keep. To summarize, the dataframe should consist of the following:
Make sure that for any new columns that you have engineered, that you've excluded the original columns from the final dataset. Otherwise, their values will interfere with the analysis later on the project. For example, you should not keep "PRAEGENDE_JUGENDJAHRE", since its values won't be useful for the algorithm: only the values derived from it in the engineered features you created should be retained. As a reminder, your data should only be from the subset with few or no missing values.
# If there are other re-engineering tasks you need to perform, make sure you
# take care of them here. (Dealing with missing data will come in step 2.1.)
azdias_below_trsh.shape
# Do whatever you need to in order to ensure that the dataframe only contains
# the columns that should be passed to the algorithm functions.
azdias_below_trsh.info()
Even though you've finished cleaning up the general population demographics data, it's important to look ahead to the future and realize that you'll need to perform the same cleaning steps on the customer demographics data. In this substep, complete the function below to execute the main feature selection, encoding, and re-engineering steps you performed above. Then, when it comes to looking at the customer data in Step 3, you can just run this function on that DataFrame to get the trimmed dataset in a single step.
# Load in the general demographics data.
customers = pd.read_csv('Udacity_CUSTOMERS_Subset.csv', delimiter=';')
customers.shape
customers.head()
# Histogram of the total missing vlaues in each feature
customers.isnull().sum().sort_values().hist(bins=25);
# Histogram of the total missing values in each row
customers.isnull().sum(axis=1).sort_values().hist();
# Missing values by features
plt.figure(figsize=(12,20))
customers.isnull().sum().sort_values().plot(kind='barh');
Cleaning function and some helper functions
import re
def convert_missing_unknown_to_nan(df, features=feat_info):
"""
Identify missing or unknown data values in the DataFrame df and convert them to NaN.
INPUT:
DataFrames df and features
OUTPUT:
cleaned DataFrame
"""
unknown_or_missing_vals = list(set(features.missing_or_unknown.unique()) - set(['[]']))
#print(unknown_or_missing_vals)
regex = re.compile(r'[-]?\d|[X]+')
for val in unknown_or_missing_vals:
if val == '[XX]':
feature_to_clean = features[features.missing_or_unknown == val].attribute.values
df[feature_to_clean] = df[feature_to_clean].replace(['XX'], np.nan)
elif val == '[-1,X]':
feature_to_clean = features[features.missing_or_unknown == val].attribute.values
df[feature_to_clean] = df[feature_to_clean].replace([-1, 'X'], np.nan)
elif val == '[-1,XX]':
feature_to_clean = features[features.missing_or_unknown == val].attribute.values
df[feature_to_clean] = df[feature_to_clean].replace([-1, 'XX'], np.nan)
else:
unknown_num_vals = regex.findall(val)
unknown_num_vals = list(map(int, unknown_num_vals))
feature_to_clean = features[features.missing_or_unknown == val].attribute.values
df[feature_to_clean] = df[feature_to_clean].replace(unknown_num_vals, np.nan)
return df
def genr(x):
"""
A function that captures generation (by decade) out of the PRAEGENDE_JUGENDJAHRE feature
INPUT:
the encoding of the PRAEGENDE_JUGENDJAHRE feature (a number between 1 and 15)
OUTPUT:
the decade of the feature (40 for 40s, 50 for 50s, etc.)
"""
if x is np.nan:
return np.nan
elif x in list(map(float, [1,2])):
return 40
elif x in list(map(float, [3,4])):
return 50
elif x in list(map(float, [5,6,7])):
return 60
elif x in list(map(float, [8,9])):
return 70
elif x in list(map(float, [10,11,12,13])):
return 80
elif x in list(map(float, [14,15])):
return 90
def movement(x):
"""
A function that captures MOVEMENT (mainstream vs. avantgarde) out of the PRAEGENDE_JUGENDJAHRE feature
INPUT:
the encoding of the PRAEGENDE_JUGENDJAHRE feature (a number between 1 and 15)
OUTPUT:
binary values (0 for 'Mainstream' and 1 for 'Avantgarde')
"""
if x is np.nan:
return np.nan
elif x in list(map(float, [1,3,5,8,10,12,14])):
return 0
elif x in list(map(float, [2,4,6,7,9,11,13,15])):
return 1
def tens_digit(x):
"""A function that splits a two digit number and returns the tens place digit"""
if x is np.nan:
return np.nan
else:
return int(x[0])
def ones_digit(x):
"""A function that splits a two digit number and returns the ones place digit"""
if x is np.nan:
return np.nan
else:
return int(x[1])
def clean_data(df, features=feat_info):
"""
Perform feature trimming, re-encoding, and engineering for demographics data
INPUT: Demographics DataFrame
OUTPUT: Trimmed and cleaned demographics DataFrame
"""
# Put in code here to execute all main cleaning steps:
# convert missing value codes into NaNs, ...
df = convert_missing_unknown_to_nan(df)
# Remove selected columns and rows, ...
remove_feats = ['AGER_TYP','GEBURTSJAHR','TITEL_KZ','ALTER_HH','KK_KUNDENTYP','KBA05_BAUMAX']
df.drop(remove_feats, axis=1, inplace=True)
# Separate observations with missing values above and below a fixed threshold
ind_below_trsh = df.isnull().sum(axis=1).values <=25
df_below_trsh = df.iloc[ind_below_trsh]
df_above_trsh = df.iloc[~ind_below_trsh]
# Select, re-encode, and engineer column values.
cat_feats = list(set(features[features.type == 'categorical'].attribute.values )-set(remove_feats))
df_cat = df_below_trsh[cat_feats]
retain_cat_feats = list(df_cat.nunique()[df_cat.nunique().values < 3].keys())
drop_cat_feats = list(set(cat_feats) - set(retain_cat_feats))
df_below_trsh = df_below_trsh.drop(drop_cat_feats, axis=1)
df_below_trsh['OST_WEST_KZ'] = df_below_trsh['OST_WEST_KZ'].map({'O':0, 'W':1})
df_below_trsh['GENERATION']=df_below_trsh.PRAEGENDE_JUGENDJAHRE.map(genr)
df_below_trsh['MOVEMENT']=df_below_trsh.PRAEGENDE_JUGENDJAHRE.map(movement)
df_below_trsh['WEALTH']=df_below_trsh.CAMEO_INTL_2015.map(tens_digit)
df_below_trsh['LIFE_STAGE']=df_below_trsh.CAMEO_INTL_2015.map(ones_digit)
mixed_feats = list(features[features.type=='mixed'].attribute.values)
mixed_feats = list(set(mixed_feats) - set(remove_feats))
df_below_trsh = df_below_trsh.drop(mixed_feats, axis=1)
# Return the cleaned dataframe.
return df_below_trsh
Before we apply dimensionality reduction techniques to the data, we need to perform feature scaling so that the principal component vectors are not influenced by the natural differences in scale for features. Starting from this part of the project, you'll want to keep an eye on the API reference page for sklearn to help you navigate to all of the classes and functions that you'll need. In this substep, you'll need to check the following:
.fit_transform() method to both fit a procedure to the data as well as apply the transformation to the data at the same time. Don't forget to keep the fit sklearn objects handy, since you'll be applying them to the customer demographics data towards the end of the project.# If you've not yet cleaned the dataset of all NaN values, then investigate and
# do that now.
display((azdias_below_trsh.isnull().sum()==0).mean())
display((azdias_below_trsh.isnull().sum(axis=1)==0).mean())
# Drop all rows with missing values
azdias_below_trsh.dropna(axis=0, how='any', inplace=True)
azdias_below_trsh.shape
azdias_below_trsh.head()
# Apply feature scaling to the general population demographics data.
from sklearn.preprocessing import StandardScaler
X = StandardScaler().fit_transform(azdias_below_trsh)
X
I removed all rows with any missing values and then I used the fit_transform method of StandardScaler function.
On your scaled data, you are now ready to apply dimensionality reduction techniques.
plot() function. Based on what you find, select a value for the number of transformed features you'll retain for the clustering part of the project.# Apply PCA to the data.
from sklearn.decomposition import PCA
pca = PCA()
X_pca = pca.fit_transform(X)
# Investigate the variance accounted for by each principal component.
from functools import partial
round_3 = partial(round, ndigits=3)
np.array(list(map(round_3, pca.explained_variance_ratio_)))
def scree_plot(pca):
'''
Creates a scree plot associated with the principal components
INPUT: pca - the result of instantian of PCA in scikit learn
OUTPUT: None
'''
num_components=len(pca.explained_variance_ratio_)
ind = np.arange(num_components)
vals = pca.explained_variance_ratio_
cumvals = np.cumsum(vals)
plt.figure(figsize=(20, 10))
ax = plt.subplot(111)
ax.bar(ind, vals)
ax.scatter(ind, cumvals, zorder=3)
ax.plot(ind, cumvals, ls=':', color='orange')
for i in range(num_components):
ax.annotate("{:.2f}%".format(vals[i]*100), (ind[i]+0.8, vals[i]),
va='bottom', ha="center", rotation=45, fontsize=10)
for i in range(1, num_components):
ax.annotate(r"%s%%" % ((str(cumvals[i]*100)[:4])), (ind[i], cumvals[i] - 0.02),
ha="left", rotation=-45, fontsize=12, color='gray')
ax.xaxis.set_tick_params(width=0)
ax.yaxis.set_tick_params(width=2, length=8)
ax.set_xlabel("Principal Component")
ax.set_ylabel("Variance Explained (%)")
plt.title('Explained Variance Per Principal Component')
plt.grid(b=True, linewidth=0.5)
scree_plot(pca)
# Re-apply PCA to the data while selecting for number of components to retain.
for ncomp in range(37, 45):
pca = PCA(ncomp)
X_pca = pca.fit_transform(X)
vals = pca.explained_variance_ratio_
cumvals = np.cumsum(vals)
if cumvals[-1] > .95:
print("{:.2f}% of the variance can be explained with only {} components.".format(cumvals[-1]*100, ncomp))
break
About 95% of the variance can be explained with only 42 components. So, I am going to retain 42 principal components in the next step.
Now that we have our transformed principal components, it's a nice idea to check out the weight of each variable on the first few components to see if they can be interpreted in some fashion.
As a reminder, each principal component is a unit vector that points in the direction of highest variance (after accounting for the variance captured by earlier principal components). The further a weight is from zero, the more the principal component is in the direction of the corresponding feature. If two features have large weights of the same sign (both positive or both negative), then increases in one tend to be associated with increases in the other. To contrast, features with different signs can be expected to show a negative correlation: increases in one variable should result in a decrease in the other.
pca.components_.shape
pca.components_
# Construct a dataframe by mapping weights for the principal components to corresponding feature names
pca_result = pd.DataFrame(pca.components_, index=['Dimension_{}'.format(num) for num in range(1, len(pca.components_)+1)],
columns=azdias_below_trsh.columns)
pca_result['Explained-Variance'] = pca.explained_variance_ratio_
pca_result = pca_result[['Explained-Variance'] + list(azdias_below_trsh.columns)]
pca_result.head()
# Each principal component is a unit vector
for i in range(len(pca.components_)):
norm_i = np.dot(pca_result.iloc[i][1:], pca_result.iloc[i][1:])
assert (norm_i-1.0) < 1e-14
# Map weights for a specified principal component to corresponding feature names
# and then print the linked values, sorted by weight.
# HINT: Try defining a function here or in a new cell that you can reuse in the
# other cells.
def color_code(x):
if x:
return '#3498db'
return '#e74c3c'
def sorted_feature_weights(n_comp=1):
"""
Maps weights for a specified principal component to corresponding feature names
and then generates a bar-plot of the linked values, sorted by weight.
"""
if n_comp < 1 or n_comp > pca_result.shape[0]:
print('Enter a valid component number (between 1 and {}.)'.format(pca_result.shape[0]))
else:
vect = pd.DataFrame(pca_result.iloc[n_comp - 1][1:].sort_values())
vect['Positive'] = vect[vect.columns[0]] > 0.0
ind = range(vect.shape[0])
plt.figure(figsize=(10,20))
ax = plt.barh(ind, vect[vect.columns[0]], color=vect.Positive.map(color_code), alpha=0.8)
plt.yticks(ind, vect.index)
sorted_feature_weights(1)
# Map weights for the second principal component to corresponding feature names
# and then print the linked values, sorted by weight.
sorted_feature_weights(2)
# Map weights for the third principal component to corresponding feature names
# and then print the linked values, sorted by weight.
sorted_feature_weights(3)
I think the above plots of the weights of the features in the principal components are very informative. For example, for the first principal component, the major features with larger positive weights are associated with the number of larger family houses in the region, wealth, estimated household net income, size of the community, density of households per square kilometer, and money saving habits, in that order. On the other hand, the major features with larger negative weights for the first principal component are associated with movement patterns, low financial interests, number of smaller family houses in the region, distance from building to point of sale, and distance to city center.
For the second principal component the major features that contribute positively include: estimated age, event-orientedness, financial preparedness, sensual-mindedness, return type, and homeownership. On the other hand, the features that contribute negatively include: being religious, generation, dutifulness, traditional-mindedness, financial inconspicuousness, and cultural-mindedness.
For the third principal component, the major features that contribute positively include: personal typology such as dreamfulness, social-mindedness, family-mindedness, cultural-mindedness, low financial interest, return type. On the other hand, the features that contribute negatively include: gender, combative attitude, dominant-mindedness, critical-mindedness, being rational, and being an investor.
You've assessed and cleaned the demographics data, then scaled and transformed them. Now, it's time to see how the data clusters in the principal components space. In this substep, you will apply k-means clustering to the dataset and use the average within-cluster distances from each point to their assigned cluster's centroid to decide on a number of clusters to keep.
.score() method might be useful here, but note that in sklearn, scores tend to be defined so that larger is better. Try applying it to a small, toy dataset, or use an internet search to help your understanding.# Over a number of different cluster counts...
from mpl_toolkits.mplot3d import Axes3D
from sklearn.cluster import KMeans
from sklearn.decomposition import PCA
from sklearn.preprocessing import StandardScaler
def plot_data(data, labels):
'''
Plot data with colors associated with labels
'''
fig = plt.figure(figsize=(10,10));
ax = Axes3D(fig)
ax.scatter(data[:,0], data[:,2], data[:,5], c=labels, cmap='tab10');
def get_kmeans_score(data, center):
'''
returns the kmeans score regarding SSE for points to centers
INPUT:
data - the dataset you want to fit kmeans to
center - the number of centers you want (the k value)
OUTPUT:
score - the SSE score for the kmeans model fit to the data
'''
#instantiate kmeans
kmeans = KMeans(n_clusters=center)
# Then fit the model to your data using the fit method
model = kmeans.fit(data)
# Obtain a score related to the model fit
score = np.abs(model.score(data))
return score
def fit_mods(data):
scores = []
centers = list(range(1,11))
for center in centers:
scores.append(get_kmeans_score(data, center))
return centers, scores
def plot_sse_vs_k(centers, scores):
"""
Generates a line plot of SSE (scores) vs. K (number of centers)
INPUT: centers, scores
OUTPUT: none
"""
plt.figure(figsize=(12,6))
plt.plot(centers, scores, linestyle='--', marker='o');
plt.xlabel('K');
plt.ylabel('SSE');
plt.title('SSE vs. K');
X = StandardScaler().fit_transform(azdias_below_trsh)
pca = PCA(42)
X_pca = pca.fit_transform(X)
# run k-means clustering on the data with n_clusters = 4
kmeans_4 = KMeans(n_clusters = 4)
model_4 = kmeans_4.fit(X_pca)
labels_4 = model_4.predict(X_pca)
plot_data(X_pca, labels_4)
data = X_pca
# compute the average within-cluster distances.
centers, scores = fit_mods(data)
# Investigate the change in within-cluster distance across number of clusters.
# HINT: Use matplotlib's plot function to visualize this relationship.
plot_sse_vs_k(centers, scores)
# Re-fit the k-means model with the selected number of clusters and obtain
# cluster predictions for the general population demographics data.
kmeans_3 = KMeans(n_clusters=3)
model_3 = kmeans_3.fit(X_pca)
labels_3 = model_3.predict(X_pca)
plot_data(X_pca, labels_3)
The SSE score vs K plot above shows that the decreases in SSE scores as K increases from 1 to 2 and from 2 to 3 are relatively subtantial, whereas from K=3 onwards, we only see a very gradual decrease in the SSE score. For this reason, I have decided to segment the population into three clusters.
Now that you have clusters and cluster centers for the general population, it's time to see how the customer data maps on to those clusters. Take care to not confuse this for re-fitting all of the models to the customer data. Instead, you're going to use the fits from the general population to clean, transform, and cluster the customer data. In the last step of the project, you will interpret how the general population fits apply to the customer data.
;) delimited.clean_data() function you created earlier. (You can assume that the customer demographics data has similar meaning behind missing data patterns as the general demographics data.).fit() or .fit_transform() method to re-fit the old objects, nor should you be creating new sklearn objects! Carry the data through the feature scaling, PCA, and clustering steps, obtaining cluster assignments for all of the data in the customer demographics data.# Load in the customer demographics data.
customers = pd.read_csv('Udacity_CUSTOMERS_Subset.csv', delimiter=';')
customers.shape
Apply preprocessing, feature transformation, and clustering from the general demographics onto the customer data, obtaining cluster predictions for the customer demographics data.
customers_clean = clean_data(customers)
customers_clean.shape
customers_clean.isnull().sum().sum()
# Remove all rows with any missing values
customers_clean.dropna(axis=0, how='any', inplace=True)
customers_clean.shape
scaler = StandardScaler().fit(azdias_below_trsh)
X = scaler.transform(azdias_below_trsh)
pca = PCA(42)
pca.fit(X)
X_pca = pca.transform(X)
kmeans = KMeans(3)
model = kmeans.fit(X_pca)
labels_gen = model.predict(X_pca)
X_customer = scaler.transform(customers_clean)
X_customer_pca = pca.transform(X_customer)
labels_cust = model.predict(X_customer_pca)
plot_data(X_customer_pca, labels_cust)
At this point, you have clustered data based on demographics of the general population of Germany, and seen how the customer data for a mail-order sales company maps onto those demographic clusters. In this final substep, you will compare the two cluster distributions to see where the strongest customer base for the company is.
Consider the proportion of persons in each cluster for the general population, and the proportions for the customers. If we think the company's customer base to be universal, then the cluster assignment proportions should be fairly similar between the two. If there are only particular segments of the population that are interested in the company's products, then we should see a mismatch from one to the other. If there is a higher proportion of persons in a cluster for the customer data compared to the general population (e.g. 5% of persons are assigned to a cluster for the general population, but 15% of the customer data is closest to that cluster's centroid) then that suggests the people in that cluster to be a target audience for the company. On the other hand, the proportion of the data in a cluster being larger in the general population than the customer data (e.g. only 2% of customers closest to a population centroid that captures 6% of the data) suggests that group of persons to be outside of the target demographics.
Take a look at the following points in this step:
countplot() or barplot() function could be handy..inverse_transform() method of the PCA and StandardScaler objects to transform centroids back to the original data space and interpret the retrieved values directly.# Compare the proportion of data in each cluster for the customer data to the
# proportion of data in each cluster for the general population.
import seaborn as sns
plt.figure(figsize=(16,6))
plt.subplot(1,2,1)
ax=sns.countplot(labels_gen)
for i in range(3):
# Note: azdias_below_trsh is about 89.5% of the general population, hence the multiplication by prop_below ~ 0.895
plt.text(i,(labels_gen==i).sum()+1500,"{:.1f}%".format((labels_gen==i).mean()*100*prop_below))
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
plt.title('Proportion of the General Population in Cluster',size=16)
plt.subplot(1,2,2)
ax=sns.countplot(labels_cust)
for i in range(3):
plt.text(i,(labels_cust==i).sum()+1000,"{:.1f}%".format((labels_cust==i).mean()*100))
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
plt.title('Proportion of Customers in Cluster',size=16);
# What kinds of people are part of a cluster that is overrepresented in the
# customer data compared to the general population?
# What kinds of people are part of a cluster that is underrepresented in the
# customer data compared to the general population?
def color_code(x):
if x:
return '#3498db'
return '#e74c3c'
def plot_inv_transforms(centroid):
"""
Applies the pca.inverse_transform() function to the kmeans cluster centers and
plots the scaled coefficients of the features.
"""
if centroid < 0 or centroid > 3:
print('Enter a valid centroid (between 0 and 2 inclusive).')
else:
center = pca.inverse_transform(kmeans.cluster_centers_[centroid])
features = pd.DataFrame(center, index=azdias_below_trsh.columns, columns=['scaled_coeffs'])
features = features.sort_values(by='scaled_coeffs')
features['Positive'] = features['scaled_coeffs'] > 0.0
ind = range(len(features.index))
plt.figure(figsize=(10,20))
ax = plt.barh(ind, features['scaled_coeffs'], color=features.Positive.map(color_code), alpha=0.8)
plt.yticks(ind, features.index)
plot_inv_transforms(0)
plot_inv_transforms(1)
plot_inv_transforms(2)
The proportion of persons in each of the three clusters appear to be different between the general population and the cutomer base. The proportion of persons in the third cluster for each of the two groups is higher, but particularly over-represented in the customer base. Looking at the plots above of the scaled coefficients of the features obtained using pca.inverse_transform applied to the kmeans cluster centers indicate that these over-represented customer base include people characterized by: low financial interest, their movement patterns, number of smaller family houses in the area, and number of buildings in the area. On the other hand, persons in the first and second clusters are under represented in the customer base as compared to the general population, more so people that belong in the second cluster. From the first of the three bar-plots above, we can deduce that these people could be that can be characterized by their: dutifulness, traditional-mindedness, religiousness, and people that are money savers, among others.
Looking at the subset of the orginal dataset with a lot of missing values
def clean_data_v2(df, features=feat_info):
"""
Perform feature trimming, re-encoding, and engineering for demographics data
INPUT: Demographics DataFrame
OUTPUT: Trimmed and cleaned demographics DataFrame
"""
df_clean = df.copy()
# Remove selected columns and rows, ...
remove_feats = ['AGER_TYP','GEBURTSJAHR','TITEL_KZ','ALTER_HH','KK_KUNDENTYP','KBA05_BAUMAX']
# Select, re-encode, and engineer column values.
cat_feats = list(set(features[features.type == 'categorical'].attribute.values )-set(remove_feats))
df_cat = df_clean[cat_feats]
retain_cat_feats = list(df_cat.nunique()[df_cat.nunique().values < 3].keys())
drop_cat_feats = list(set(cat_feats) - set(retain_cat_feats))
df_clean = df_clean.drop(drop_cat_feats, axis=1)
df_clean['OST_WEST_KZ'] = df_clean['OST_WEST_KZ'].map({'O':0, 'W':1})
df_clean['GENERATION']=df_clean.PRAEGENDE_JUGENDJAHRE.map(genr)
df_clean['MOVEMENT']=df_clean.PRAEGENDE_JUGENDJAHRE.map(movement)
df_clean['WEALTH']=df_clean.CAMEO_INTL_2015.map(tens_digit)
df_clean['LIFE_STAGE']=df_clean.CAMEO_INTL_2015.map(ones_digit)
mixed_feats = list(features[features.type=='mixed'].attribute.values)
mixed_feats = list(set(mixed_feats) - set(remove_feats))
df_clean = df_clean.drop(mixed_feats, axis=1)
# Return the cleaned dataframe.
return df_clean
azdias_above = clean_data_v2(azdias_above_trsh)
azdias_above[azdias_above.isnull().sum(axis=1) == 0]
Note: there are no rows in the azdias_above dataframe that don't have missing values. So, I will fill the missing ...
from sklearn.preprocessing import Imputer
azdias_above.shape
selector = (azdias_above.isnull().sum().sort_values(ascending=False)==azdias_above.shape[0]).values
feats_all_nan = azdias_above.isnull().sum().sort_values(ascending=False).keys()[selector]
imp = Imputer(strategy='median')
azdias_above_fill = azdias_above.drop(feats_all_nan, axis=1)
azdias_above_fill_imp =imp.fit_transform(azdias_above_fill)
scaler = StandardScaler().fit(azdias_above_fill_imp)
X = scaler.transform(azdias_above_fill_imp)
pca = PCA(42)
pca.fit(X)
X_pca = pca.transform(X)
kmeans = KMeans(1)
model = kmeans.fit(X_pca)
labels = model.predict(X_pca)
def color_code(x):
if x:
return '#3498db'
return '#e74c3c'
def plot_inv_transform():
"""
Applies the pca.inverse_transform() function to the kmeans cluster centers and
plots the scaled coefficients of the features.
"""
center = pca.inverse_transform(kmeans.cluster_centers_[0])
features = pd.DataFrame(center, index=azdias_above_fill.columns, columns=['scaled_coeffs'])
features = features.sort_values(by='scaled_coeffs')
features['Positive'] = features['scaled_coeffs'] > 0.0
ind = range(len(features.index))
plt.figure(figsize=(10,20))
ax = plt.barh(ind, features['scaled_coeffs'], color=features.Positive.map(color_code), alpha=0.8)
plt.yticks(ind, features.index)
plot_inv_transform()
Remark: it appears that the people in the subset with a lot of missing values are those that can be characterized in terms of features that mainly include: first year building was mentioned in the database ("MIN_GEBAUEUDEJAHR"), neighborhood typology ("REGIOTYP"), and wealth.
Congratulations on making it this far in the project! Before you finish, make sure to check through the entire notebook from top to bottom to make sure that your analysis follows a logical flow and all of your findings are documented in Discussion cells. Once you've checked over all of your work, you should export the notebook as an HTML document to submit for evaluation. You can do this from the menu, navigating to File -> Download as -> HTML (.html). You will submit both that document and this notebook for your project submission.